//
//  DAPersonalViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/4/26.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAPersonalViewController.h"
#import "DALabel.h"
#import "DAAlertView.h"
#import "Utility.h"
#import "DAPersonalSettingViewController.h"
#import "DAPersonalBorrowBookTableViewCell.h"
#import "DAPersonalBookHistoryTableViewCell.h"
#import "DAPersonalBorrowBookStatusView.h"
#import "DAHomePageShowBookDetailViewController.h"
#import "DASearchBookDetailViewController.h"
#import "DAloginPersonalInformation.h"
#import "DAHomePageTimeLineModel.h"
#import "DAPersonalBookManageModel.h"
#import "DAInputBookLostReasonView.h"
#import "DABookDelayView.h"
#import "DARateNumberAndRateMessage.h"
#import "DAPersonalBackBookTableViewCell.h"
#import "DAOtherPersonalViewController.h"
#import "DATabBarViewController.h"
#import "DAPersonalFileUploadTableViewCell.h"
#import "DAWebFileViewController.h"
#import "DAUserFileModel.h"
#import "DAPersonalFileListTableViewCell.h"
#import "DAPersonalFileListModel.h"
#import "DANetWorkReachabilityStatus.h"
#import "DACollectedFilesViewController.h"


typedef void(^backBookBlock) (void);

@interface DAPersonalViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDataSource, UITableViewDelegate, clickCancel, showBookStatus, clickBookImage, postBookLostMessage, bookDelayDelegate, rateMessageViewDelegate, personalBckBookClickBookImage, PersonalFileUploadDelegate>{
    UIView *topView;
    UISegmentedControl *bookSegment;
    UILabel *label;
}
@property (nonatomic, strong) NSMutableArray *keys; //存储key值
@property (nonatomic, strong) NSMutableArray *indexArray; //索引数组
@property (nonatomic, strong) NSMutableArray *charactorArray; //A-Z 数组
@property (nonatomic, strong) NSMutableDictionary *userDic;
/** 背景墙*/
@property (nonatomic, strong) UIImageView *backgroundWall;
/** 用户头像*/
@property (nonatomic, strong) UIImageView *userImage;
/** 用户名*/
@property (nonatomic, strong) DALabel *userNameLabel;
/** 个性签名*/
@property (nonatomic, strong) DALabel *personalSignatureLabel;
/** 背景图片的路径*/
@property (nonatomic, strong) NSString *backgroundImagePath;
/** 用户头像的路径*/
@property (nonatomic, strong) NSString *userImagePath;
/** 是否选择了背景墙*/
@property (nonatomic) BOOL isSelectedBackgroundWall;
/** 是否选择了用户头像*/
@property (nonatomic) BOOL isSelectedUserImage;
/** 用户判断时间轴和图书管理状态的改变 */
@property (nonatomic) NSInteger changeStatus;
/** 搜索的image */
@property (nonatomic, strong) UIImageView *searchImageView;
/** tableView */
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** 点击图书管理页面的图书 出现的背景 */
@property (nonatomic, strong) UIView *backView;
/** 点击图书出现的图书状态的页面 */
@property (nonatomic, strong) DAPersonalBorrowBookStatusView *statusView;
/** 用来保存从相册选取或者相机拍摄的图片*/
@property (nonatomic, strong) UIImage *selectImage;
/** 灰色蒙版*/
@property (nonatomic, strong) UIView *grayView;
@property(nonatomic, strong) DAHomePageShowBookDetailViewController *detailView;
/** 个人信息的model*/
@property (nonatomic, strong) DAloginPersonalInformation *personalInformation;
@property (nonatomic, strong) NSMutableArray *personalBookManageArray;
@property (nonatomic, strong) DAPersonalBookManageModel *personalBookManageModel;
/** 保存数据的数组*/
@property (nonatomic, strong) NSMutableArray *personalDataArray;
@property (nonatomic, strong) NSMutableArray *personalBookManageModelArray;
@property (nonatomic, strong) NSMutableArray *threeBookMnanageArray;
@property (nonatomic, strong) NSMutableArray *fileManagmentArray;
@property (nonatomic, assign) NSInteger personalTimelinePageNumber;
@property (nonatomic) BOOL isPersonalTimeLineRefresh;
@property (nonatomic, assign) NSInteger personalBookManagementPageNumber;
@property (nonatomic, assign) NSInteger personalFileManagmentPageNumber;
@property (nonatomic) BOOL isPersonalBookManagementRefresh;
@property (nonatomic) BOOL isPersonalFileManagmentRefresh;
@property (nonatomic, strong) DAInputBookLostReasonView *InputBookLostReasonView;
@property (nonatomic, copy) backBookBlock backBookBlock;
@property (nonatomic, strong) UILabel *topViewNameLabel;
@property (nonatomic, strong) UIImageView *topViewUserImage;
@property (nonatomic, strong) DABookDelayView *bookDelayView;
@property (nonatomic, strong) DARateNumberAndRateMessage *rateMessageView;
@property (nonatomic, strong) NSMutableArray *collectFiles;

// 用于存储个人信息
@property (nonatomic, copy) NSString *userBackground;
@property (nonatomic, copy) NSString *userFace;
@property (nonatomic, copy) NSString *userName;

@property (nonatomic, copy) NSString *borrowExtendBookID;

@property (nonatomic, copy) NSString *borrowID;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *footer;



@end

@implementation DAPersonalViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [SVProgressHUD dismiss];
    /** 发送通知 显示tabBar*/
    [[NSNotificationCenter defaultCenter]postNotificationName:@"showTabBar" object:nil];
    // 获取个人时间轴的数据
    // [self preparePersonalTimelineData];
    // 获取个人的借书管理数据
    // [self getPersonalBorrowBook];
    // [self prepareData];
    // [self prepareFileData];
    [self setupBackWall];
    [self updateUserInfo];
    
    //    static dispatch_once_t onceToken;
    //    dispatch_once(&onceToken, ^{
    //        [self.tableView.mj_header beginRefreshing];
    //    });
    
    [self setNotific];
    
}
// 注册通知
- (void)setNotific{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(grayViewRemove) name:@"GRAYVIEWREMOVE" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"REFRESH" object:nil];
    
    
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(turnPersonalPage:) name:@"TurnPersonalPage" object:nil];
}
- (void)turnPersonalPage:(NSNotification *)not{
    
    [self clickClose:nil];
    [self turnPersonal:not.object];
}

- (void)grayViewRemove{
    [self.grayView removeFromSuperview];
}
#pragma mark - 每次进入这个页面 实时获取一下user信息
- (void)GetuserInfo{
    
}
#pragma mark - 背景墙和个人头像的一些设置
- (void)setupBackWall{
    if (self.selectImage == nil) {
        // 获取 背景墙的数据 如果为空 设置默认的背景图片
        if (self.personalInformation.userBackground == nil) {
            /**  需要添加一个默认的背景图片*/
            self.backgroundWall.image = [UIImage imageNamed:@"background.jpg"];
            self.backgroundWall.clipsToBounds = YES;
        } else {
            self.backgroundWall.image = [UIImage imageNamed:@"background.jpg"];
            self.backgroundWall.clipsToBounds = YES;
        }
        // 获取 个人头像的数据 如果为空 设置默认的头像
        if (self.personalInformation.userFace == nil) {
            /**  需要添加一个默认的头像图片*/
            self.userImage.image = [UIImage imageNamed:@""];
            self.userImage.clipsToBounds = YES;
        } else {
            [self.userImage sd_setImageWithURL:[NSURL URLWithString:self.personalInformation.userFace] placeholderImage:[UIImage imageNamed:@"holderface"] options:SDWebImageRefreshCached];
            
            self.backgroundWall.clipsToBounds = YES;
        }
    } else {
        if (self.isSelectedUserImage) {
            
        } else if (self.isSelectedBackgroundWall) {
            
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 调用从本地获取数据
    [self prepareData];
    /** 调用导航栏设置的方法*/
    [self setHiddenNavgationBar];
    /** 调用创建背景墙的方法*/
    [self setUpBackgroundWall];
    /** 调用创建图片路径的方法*/
    [self creatImagePath];
    /** 调用创建tableView的方法*/
    [self creatTableView];
    /** 创建个人借阅历史中的图书详情*/
    [self buildBookDetailView];
    /** 创建个人图书管理里图书状态的页面*/
    [self creatStatusView];
    // 设置 个人时间轴的 page 和是否刷新的状态
    self.personalTimelinePageNumber = 0;
    self.isPersonalTimeLineRefresh = YES;
    // 设置 图书管理的 page  和是否刷新的状态
    self.personalBookManagementPageNumber = 0;
    self.isPersonalBookManagementRefresh = YES;
    
    //无文件时显示的Label
    label = [[UILabel alloc]init];
    label.text = NSLocalizedString(@"nofile", nil);
    label.frame = CGRectMake(20, self.view.frame.size.height *0.5, self.view.frame.size.width-40, 80);
    label.font = [UIFont fontWithName:@"Helvetica-Bold" size:19];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor colorWithHexString:bookTypeColor];
    [self.tableView addSubview:label];
    label.hidden = YES;
    
    // 点击相同阅读者 跳入其他人的页面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(turnPersonalPage:) name:@"TurnPersonalPage" object:nil];
    
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark - 从本地获取数据
- (void)prepareData{
    /** 解档*/
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"DALogin"];
    self.personalInformation = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    // NSLog(@"!!!!!!!!!%@", self.personalInformation.userFace);
}
#pragma mark - tableView设置
- (void)creatTableView{
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.sectionIndexColor = [UIColor colorWithHexString:backButtonColor];
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.editing = NO;
    
    
    
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    //    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    //    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
    
    //  self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    
    self.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = self.footer;
    self.tableView.mj_footer.hidden = YES;
    //    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    //    self.tableView.mj_footer.hidden = YES;
    
}
#pragma mark - !!! 数据刷新
- (void)refreshData{
    // 更新个人信息
    
    if (self.changeStatus == 1) {
        self.isPersonalBookManagementRefresh = YES;
        self.personalBookManagementPageNumber = 0;
        [self getPersonalBorrowBook];
    }else if(self.changeStatus == 0){
        self.isPersonalTimeLineRefresh = YES;
        self.personalTimelinePageNumber = 0;
        [self prepareData];
        [self preparePersonalTimelineData];
    }else{
        [self prepareFileData];
    }
}
#pragma mark - 上拉刷新
- (void)loadMoreData{
    if (self.changeStatus == 1) {
        self.isPersonalBookManagementRefresh = NO;
        self.personalBookManagementPageNumber++;
        [self getPersonalBorrowBook];
    }else if(self.changeStatus == 0){
        self.isPersonalTimeLineRefresh = NO;
        self.personalTimelinePageNumber++;
        [self preparePersonalTimelineData];
    }
}
#pragma mark - tablView 协议方法
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (bookSegment.selectedSegmentIndex == 0) {
        
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsMake(0, 60, 0, 0)];
        }
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsMake(0, 60, 0, 0)];
        }
    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.changeStatus == 2) {
        return self.indexArray.count;
    }else{
        return 1;
    }
}
//索引内容
//- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
//    if (self.changeStatus == 2) {
//        return self.indexArray;
//    }else{
//        return nil ;
//    }
//}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.changeStatus == 2) {
        return [self.indexArray objectAtIndex:section];
    }else{
        return nil;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    /** 根据当前选中的状态 来判断 时间轴 还是图书管理 来分配cell的数量*/
    if (self.changeStatus == 1) {
        return self.threeBookMnanageArray.count;
    }else if(self.changeStatus == 0){
        return self.personalDataArray.count;
    }else{
        NSString *key = self.indexArray[section];
        NSArray *arr = [self.userDic objectForKey:key];
        return [arr count];
    }
}

//TableViewCell进入编辑模式
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//
//
//}

//判断是否是需要 可编辑 的Cell
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.changeStatus == 0 || self.changeStatus == 1) {
        return  NO;
    } else{
        return  YES;
    }
    
}

//Cell左划出现多个按钮
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //删除按钮
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSString *key = self.indexArray[indexPath.section];
        NSArray *arr = [self.userDic objectForKey:key];
        DAPersonalFileListTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        if (cell.userFileModel.isDownloading) {
            //NSLog(@"正在下载");
            [SVProgressHUD showInfoWithStatus:@"正在下载,请勿删除"];
        }else{
            //NSLog(@"删除文件的ID %@",cell.userFileModel.fileID);
            //删除 文件  本地&&Sever
            
            //删除文件
            NSString *URL = DADeleteUserFile;
            NSDictionary *dic;
            dic = @{@"fileID": cell.userFileModel.fileID ,@"filefolderName":cell.userFileModel.filefolderName};
            //[SVProgressHUD show];
            [DADataHandel postURL:URL parame:dic cookie:nil result:^(id result) {
                if (result) {
                    NSLog(@"结果 %@",result);
                    if([result[@"result"]isEqualToString:@"true"]){
                        NSLog(@"服务器端删除成功!!");
                        
                        //删除本地文件
                        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                        NSString *documentsDirectory = [paths objectAtIndex:0];
                        NSString *path = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, cell.userFileModel.filefolderName , cell.userFileModel.fileExtend];
                        NSLog(@"删除文件 %@",path);
                        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
                        }
                        
                        //删除TableViewCell
                        [self.fileManagmentArray removeObject:cell.userFileModel];
                        //更新  索引数组
                        [self arraySort];
                        if (arr.count == 1) {
                            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex: indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                        }else{
                            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationFade];
                        }
                        [self.tableView reloadData];
                        //[SVProgressHUD dismiss];
                    }else{
                        NSLog(@"服务器端删除失败");
                        NSString *str = NSLocalizedString(@"deletefilefail", nil);
                        [SVProgressHUD showSuccessWithStatus:str];
                        //[SVProgressHUD dismiss];
                    }
                } else {
                    NSLog(@"网络异常");
                }
                // [SVProgressHUD dismiss];
            }];
            // NSLog(@"文件 %@", p);
        }
        
    }];

    //收藏&取消收藏
//    NSString *key = self.indexArray[indexPath.section];
//    NSMutableArray *arr = [self.userDic objectForKey:key];
//    DAUserFileModel *model = [arr objectAtIndex:indexPath.row];
//    BOOL flag = [[DACollectionFiles shareDACollectionFiles] isContainCollectionsWith:model.fileID];
//    if (!flag) {
//        //收藏按钮
//        UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"收藏" handler:^(UITableViewRowAction *_Nonnull action, NSIndexPath * _Nonnull indexPath){
//            NSLog(@"收藏");
//            NSDictionary *dic;
//            NSString *url = DACollectionFile;
//            dic = @{@"collectUserID":self.userID , @"collectFolderName":model.filefolderName};
//            
//            [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
//                if (result) {
//                    NSLog(@"结果 %@",result);
//                    //NSLog(@"收藏成功!");
//                    [SVProgressHUD showSuccessWithStatus:@"收藏成功"];
//                    //[self.collectFiles addObject:model];
//                    [[DACollectionFiles shareDACollectionFiles] updateWithUserID:self.userID Block:^(NSMutableArray *array) {
//                        self.collectFiles = array;
//                    }];
//                    if (tableView == self.tableView) {
//                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                    }else{
//                        [self.searchDisplayController.searchResultsTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                    }
//                }else{
//                    // NSLog(@"收藏失败!");
//                    [SVProgressHUD showErrorWithStatus:@"收藏失败"];
//                }
//            }];
//            //NSLog(@"用户 : %@  文件 : %@",self.userID,model.filefolderName);
//        }];
//        collectRowAction.backgroundColor = [UIColor orangeColor];
//        //  [self prepareCollectFiles];
//        return  @[deleteRowAction,collectRowAction];
//    }else{
//        //取消收藏按钮
//        UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"取消收藏" handler:^(UITableViewRowAction *_Nonnull action, NSIndexPath * _Nonnull indexPath){
//            NSLog(@"取消收藏");
//            NSDictionary *dic;
//            NSString *url = DACancelCollectionFile;
//            dic = @{@"collectUserID":self.userID , @"collectFolderName":model.filefolderName};
//            
//            [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
//                NSLog(@"结果 %@",result);
//                if (result) {
//                    //NSLog(@"收藏成功!");
//                    [SVProgressHUD showSuccessWithStatus:@"取消收藏成功"];
//                    //[self.collectFiles removeObject:trans];
//                    [[DACollectionFiles shareDACollectionFiles]updateWithUserID:self.userID Block:^(NSMutableArray *array) {
//                        self.collectFiles = array ;
//                    }];
//                    if (tableView == self.tableView) {
//                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                    }else{
//                        [self.searchDisplayController.searchResultsTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                    }
//                }else{
//                    NSLog(@"取消收藏失败!");
//                    [SVProgressHUD showErrorWithStatus:@"取消收藏失败"];
//                }
//            }];
//        }];
//        collectRowAction.backgroundColor = [UIColor orangeColor];
//        // [self prepareCollectFiles];
//        return @[deleteRowAction,collectRowAction];
//    }
    return @[deleteRowAction];
}


- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /** 根据当前选中的状态 来判断是时间轴还是图书管理 来显示对应的cell*/
    if (self.changeStatus == 1) {
        DAPersonalBorrowBookTableViewCell *borrow = [tableView dequeueReusableCellWithIdentifier:@"borrowHistory"];
        if (borrow == nil) {
            borrow = [[DAPersonalBorrowBookTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"borrowHistory"];
        }
        borrow.selectionStyle = UITableViewCellSelectionStyleNone;
        borrow.backgroundColor = [UIColor colorWithHexString:backGroundColor];
        borrow.delegate = self;
        // 赋值
        borrow.modelArray = self.threeBookMnanageArray[indexPath.row];
        return borrow;
    }
    else if(self.changeStatus == 0){
        if ([[self.personalDataArray[indexPath.row] timelineType] isEqualToString:@"2"]) {
            DAPersonalBackBookTableViewCell *backCell = [tableView dequeueReusableCellWithIdentifier:@"personalBackBook"];
            if (backCell == nil) {
                backCell = [[DAPersonalBackBookTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"personalBackBook"];
            }
            backCell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
            backCell.selectionStyle = UITableViewCellSelectionStyleNone;
            backCell.timeLineModel = self.personalDataArray[indexPath.row];
            backCell.delegate = self;
            return backCell;
        }else {
            if([[self.personalDataArray[indexPath.row] timelineType] isEqualToString:@"1"]){
                DAPersonalBookHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"history"];
                if (cell == nil) {
                    cell = [[DAPersonalBookHistoryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"history"];
                }
                cell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.timeLineModel = self.personalDataArray[indexPath.row];
                cell.delegate = self;
                return cell;
            } else if ([[self.personalDataArray[indexPath.row] timelineType] isEqualToString:@"3"]){
                DAPersonalFileUploadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonalFileUpload"];
                if (cell == nil) {
                    cell = [[DAPersonalFileUploadTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PersonalFileUpload"];
                }
                
                cell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.model = self.personalDataArray[indexPath.row];
                cell.delegate = self;
                return cell;
            }
            else{
                UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ss"];
                return cell;
            }
        }
        
    }else{
        
        DAPersonalFileListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"personalFileCell"];
        if (cell == nil) {
            cell = [[DAPersonalFileListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"personalFileCell"];
        }
        NSString *key = self.indexArray[indexPath.section];
        NSArray *arr = [self.userDic objectForKey:key];
        DAPersonalFileListModel *model = [arr objectAtIndex:indexPath.row];
        NSString *file = [NSString stringWithFormat:@"file_%@.png",model.fileExtend];
        UIImage *image = [UIImage imageNamed:file];
        
        cell.fileNameLabel.text = model.fileName;
        cell.fileImageView.image = image;
        cell.fileIntroduction.text = model.fileType;
        cell.fileIntroduction.textColor = [UIColor colorWithHexString:timeColor];
        cell.backgroundColor = [UIColor whiteColor];
        
        //是否已下载
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        //NSLog(@"文件保存路径%@",documentsDirectory);
        BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] inPath:documentsDirectory];
        if (isExist) {
            // fileListCell.downLoadCompleteImage.image = [UIImage imageNamed:@"complete@3x"];
            model.isDownloadingSuccessful = YES;
            //[arr replaceObjectAtIndex:indexPath.row withObject:model];
        }
        
        cell.userFileModel = model;
        
        
        //处理文件大小
        int fileSize = [model.fileSize intValue];
        float fileSizeK = 0.0;
        float fileSizeM = 0.0;
        if (fileSize > 999 && fileSize < 999*1024) {
            fileSizeK = fileSize/1024.0;
            cell.fileSize.text = [NSString stringWithFormat:@"%.2fK",fileSizeK];
        }else if (fileSize >= 999*1024 ){
            fileSizeM = fileSize/(1024.0*1024.0);
            cell.fileSize.text = [NSString stringWithFormat:@"%.2fM",fileSizeM];
        }else{
            cell.fileSize.text = [NSString stringWithFormat:@"%dB",fileSize];
        }
        cell.fileSize.textColor = [UIColor colorWithHexString:timeColor];
        
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /** 根据当前的状态 来判断cell的高度*/
    if (self.changeStatus == 1) {
        if (self.threeBookMnanageArray.count > 0) {
            if (self.view.bounds.size.width > 375) {
                return 220;
            }else if (self.view.bounds.size.width == 375){
                return 200;
            }else{
                return 180;
            }
        }else{
            return 0;
        }
        
    }else if(self.changeStatus == 0) {
        
        if (self.personalDataArray.count > 0) {
            if ([[self.personalDataArray[indexPath.row] timelineType] isEqualToString:@"2"]) {
                CGFloat textHeight = [self heightWithText:[self.personalDataArray[indexPath.row] rateMessage] Width:[UIScreen mainScreen].bounds.size.width - 125 Font:12];
                return 145 + textHeight + 48;
                
            }else{
                if ([[self.personalDataArray[indexPath.row] timelineType] isEqualToString:@"1"]) {
                    return 155;
                } else if ([[self.personalDataArray[indexPath.row] timelineType] isEqualToString:@"3"])
                    
                    return 110;
                else{
                    return 0;
                }
            }
        }else{
            return 0;
        }
        
    }else{
        return 60;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.changeStatus == 2){
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSString *key = self.indexArray[indexPath.section];
        NSMutableArray *arr = [self.userDic objectForKey:key];
        DAPersonalFileListModel *model = [arr objectAtIndex:indexPath.row];
        DAPersonalFileListTableViewCell *cell = [[DAPersonalFileListTableViewCell alloc]init] ;
        cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        //文件保存路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.filefolderName,model.fileExtend];
        //NSLog(@"文件保存路径 %@",documentsDirectory);
        NSLog(@"文件ID %@",model.fileID);
        
        
        //判断文件在本地是否存在
        if(model.isDownloading == YES){
            NSLog(@"正在下载");
        }else{
            
            BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] inPath:documentsDirectory];
            if (isExist) {
                NSLog(@"文件存在可以直接打开");
                DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
                webFile.fileUrl = filePath;
                webFile.fileID = model.fileID;
                webFile.filefolderName = model.filefolderName;
                webFile.hidesBottomBarWhenPushed = YES;
                self.navigationController.navigationBarHidden = NO;
                [self.navigationController pushViewController:webFile animated:YES];
            }else{
                //下载文件
                //判断网络连接
                [DANetWorkReachabilityStatus isNetWorkConnectWithBlock:^(BOOL isConnect){
                    if (isConnect) {
                        NSLog(@"下载文件");
                        cell.progress.hidden = NO;
                        model.isDownloading = YES;
                        [arr replaceObjectAtIndex:indexPath.row withObject:model];
                        [self.userDic setValue:arr forKey:key];
                        
                        //            dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
                        //                [self downLoadFile:[NSString stringWithFormat:@"%@.   %@",model.filefolderName,model.fileExtend] saveInPath:documentsDirectory fromURL:url];
                        //            });
                        [NSThread detachNewThreadSelector:@selector(downloadFileOnBackground:) toTarget:self withObject:indexPath];
                    }else{
                        NSString *str = NSLocalizedString(@"NoNetWorkCouldNotDownload", nil);
                        [SVProgressHUD showErrorWithStatus:str];
                    }
                }];
                //                NSLog(@"下载文件");
                //                cell.progress.hidden = NO;
                //                model.isDownloading = YES;
                //                [arr replaceObjectAtIndex:indexPath.row withObject:model];
                //                [self.userDic setValue:arr forKey:key];
                //
                //                //            dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
                //                //                [self downLoadFile:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] saveInPath:documentsDirectory fromURL:url];
                //                //            });
                //                [NSThread detachNewThreadSelector:@selector(downloadFileOnBackground:) toTarget:self withObject:indexPath];
                
                
            }
        }
        
        //        NSString *key = self.indexArray[indexPath.section];
        //        NSArray *arr = [self.userDic objectForKey:key];
        //        DAUserFileModel *model = [arr objectAtIndex:indexPath.row];
        //
        //        //文件保存路径
        //        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        //        NSString *documentsDirectory = [paths objectAtIndex:0];
        //        NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.filefolderName,model.fileExtend];
        //        NSLog(@"文件保存路径 %@",documentsDirectory);
        //
        //        //文件下载路径
        //        NSString *str = model.fileUrl;
        //        NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
        //        NSURL *url = [NSURL URLWithString:encodedString];
        //
        //        //判断文件在本地是否存在
        //        BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] inPath:documentsDirectory];
        //        if (isExist) {
        //            NSLog(@"文件存在可以直接打开");
        //            DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
        //            webFile.fileUrl = filePath;
        //            webFile.hidesBottomBarWhenPushed = YES;
        //            self.navigationController.navigationBarHidden = NO;
        //            [self.navigationController pushViewController:webFile animated:YES];
        //        }else{
        //            //下载文件
        //            NSLog(@"下载文件");
        //            dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        //                [self downLoadFile:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] saveInPath:documentsDirectory fromURL:url];
        //            });
        //        }
        //
        
        
        //        DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
        //
        //        NSString *key = self.indexArray[indexPath.section];
        //        NSArray *arr = [self.userDic objectForKey:key];
        //        DAUserFileModel *model = [arr objectAtIndex:indexPath.row];
        //        webFile.fileUrl = model.fileUrl;
        //        webFile.fileName = model.fileName;
        //        webFile.fileExtend = model.fileExtend;
        //        webFile.hidesBottomBarWhenPushed = YES;
        //        self.navigationController.navigationBarHidden = NO;
        //        [self.navigationController pushViewController:webFile animated:YES];
        
    }
}



- (void)downloadFileOnBackground:(NSIndexPath *)indexPath{
    DAPersonalFileListTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSString *key = self.indexArray[indexPath.section];
    NSArray *arr = [self.userDic objectForKey:key];
    DAUserFileModel *model = [arr objectAtIndex:indexPath.row];
    //文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"文件保存路径 %@",documentsDirectory);
    
    //文件下载路径
    NSString *str = model.fileUrl;
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
    NSURL *url = [NSURL URLWithString:encodedString];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.filefolderName,model.fileExtend];
    // NSURL *url = [NSURL URLWithString:@"http://www.abc.com/test.mp4"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task =
    //    [manager downloadTaskWithRequest:request
    //                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    //                                return [NSURL fileURLWithPath:fullPath];
    //                            }
    //                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    //
    //                   }];
    
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        CGFloat count = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell.progress setProgress:count animated:YES];
        });
        //NSLog(@"下载进度 %f",count);
        //    if (self.isFinish == NO) {
        //            [SVProgressHUD  showProgress:count];
        //        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        cell.progress.hidden = YES;
        cell.downLoadCompleteImage.image = [UIImage imageNamed:@"complete@3x"];
        model.isDownloading = NO;
        //[SVProgressHUD dismiss];
        // [self creatPreview];
    }];
    [task resume];
}

#pragma mark - DAPersonalBorrowBookTableViewCell 的协议方法
- (void)showBookStatus:(DAPersonalBookManageModel *)model
            bookStatus:(NSString *)status withColor:(UIColor *)color{
    NSString *back = NSLocalizedString(@"backBook", nil);
    NSString *lost = NSLocalizedString(@"lostBook", nil);
    
    [self showBackView];
    [self showDetailView];
    self.statusView.personalBookManageModel = model;
    [self.statusView.bookStatus setText:status fitToContent:YES];
    self.statusView.bookStatus.textColor = [UIColor supportGreenColor];
    if ([status isEqualToString:back]) {
        self.statusView.backButton.userInteractionEnabled = NO;
        self.statusView.backButton.backgroundColor = [UIColor colorWithHexString:backNowColor];
        self.statusView.lostButton.userInteractionEnabled = NO;
        self.statusView.lostButton.backgroundColor = [UIColor colorWithHexString:backNowColor];
        self.statusView.delayButton.userInteractionEnabled = NO;
        self.statusView.delayButton.backgroundColor = [UIColor colorWithHexString:backNowColor];
    }else if([status isEqualToString:lost]) {
        self.statusView.backButton.userInteractionEnabled = NO;
        self.statusView.backButton.backgroundColor = [UIColor colorWithHexString:backNowColor];
        self.statusView.lostButton.userInteractionEnabled = NO;
        self.statusView.lostButton.backgroundColor = [UIColor colorWithHexString:backNowColor];
        self.statusView.bookStatus.textColor = [UIColor colorWithHexString:lostButtonColor];
        self.statusView.delayButton.userInteractionEnabled = NO;
        self.statusView.delayButton.backgroundColor = [UIColor colorWithHexString:backNowColor];
    }else{
        self.statusView.backButton.userInteractionEnabled = YES;
        self.statusView.backButton.backgroundColor = [UIColor supportGreenColor];
        self.statusView.lostButton.userInteractionEnabled = YES;
        self.statusView.lostButton.backgroundColor = [UIColor colorWithHexString:lostButtonColor];
        self.statusView.delayButton.userInteractionEnabled = YES;
        self.statusView.delayButton.backgroundColor = [UIColor supportGreenColor];
    }
    // 创建输入框
    [self creatBookLostInputReasonView];
    // 创建评分的view
    // [self creatRateMessageView];
    
}
#pragma mark - 个人图书管理的图书状态 出现的灰色背景
- (void)showBackView{
    self.backView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.backView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:self.backView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickCancel)];
    [self.backView addGestureRecognizer:tap];
}
#pragma mark - 点击图书之后出现的动画
- (void)showDetailView{
    self.statusView.hidden = NO;
    self.statusView.tag = 1000;
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self.statusView];
    /** 添加动画*/
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.statusView cache:YES];
    [UIView commitAnimations];
}
#pragma mark - 显示bookStatusView
- (void)creatStatusView {
    self.statusView = [[DAPersonalBorrowBookStatusView alloc]initWithFrame:CGRectMake(20 , self.view.center.y - 160, self.view.frame.size.width - 40, 320)];
    [[UIApplication sharedApplication].keyWindow addSubview:self.statusView];
    if (self.view.bounds.size.width < 375) {
        self.statusView.frame = CGRectMake(20, self.view.center.y - 160 *(self.view.bounds.size.width / 375), self.view.frame.size.width - 40, 290);
    }
    self.statusView.delegate = self;
    self.statusView.hidden = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickStatusView)];
    [self.statusView addGestureRecognizer:tap];
    // 创建延期view
    [self creatDelayView];
    
    // 创建评价的view
    // [self creatRateMessageView];
}
#pragma mark - 点击statusView 让输入框消失
- (void)clickStatusView{
    [self .InputBookLostReasonView.textField resignFirstResponder];
}
#pragma mark - 实现DAPersonalBorrowBookStatusView的协议方法
- (void)clickCancel{
    self.statusView.hidden = YES;
    self.bookDelayView.hidden = YES;
    [self.backView removeFromSuperview];
    // 让输入框失去第一响应者
    [self.InputBookLostReasonView.textField resignFirstResponder];
    // 让评分的view失去第一响应者
    [self.rateMessageView.textView resignFirstResponder];
}
#pragma mark - 隐藏导航栏
- (void)setHiddenNavgationBar{
    topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 65)];
    topView.backgroundColor = [UIColor supportGreenColor];
    [self.view addSubview:topView];
    topView.alpha = 0;
    self.topViewUserImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, 25, 34, 34)];
    // [self.topViewUserImage sd_setImageWithURL:[NSURL URLWithString:self.personalInformation.userFace]];
    [self.topViewUserImage sd_setImageWithURL:[NSURL URLWithString:self.personalInformation.userFace] placeholderImage:[UIImage imageNamed:@"holderface"] options:SDWebImageRefreshCached];
    [self.topViewUserImage.layer setCornerRadius:17];
    self.topViewUserImage.clipsToBounds = YES;
    [topView addSubview:self.topViewUserImage];
    
    self.topViewNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 32, 150, 20)];
    self.topViewNameLabel.text = self.personalInformation.userName;
    self.topViewNameLabel.textColor = [UIColor whiteColor];
    self.topViewNameLabel.font = [UIFont systemFontOfSize:15];
    [topView addSubview:self.topViewNameLabel];
    
    self.navigationController.navigationBarHidden = YES;
    self.edgesForExtendedLayout = UIRectEdgeNone;
}
#pragma mark - 名字 和个性签名的更新
- (void)updateUserInfo{
    [self prepareData];
    
    if (![self.personalInformation.userName isKindOfClass:[NSNull class]]) {
        [self.userNameLabel setText:self.personalInformation.userName fitToContent:YES];
    }
    
    if (![self.personalInformation.userSign isKindOfClass:[NSNull class]] ) {
        [self.personalSignatureLabel setText:self.personalInformation.userSign fitToContent:YES];
    }
    // topView 上的头像和用户名
    if (![self.personalInformation.userName isKindOfClass:[NSNull class]]) {
        self.topViewNameLabel.text = self.personalInformation.userName;
    }
    // [self.topViewUserImage sd_setImageWithURL:[NSURL URLWithString:self.personalInformation.userFace]];
    [self.topViewUserImage sd_setImageWithURL:[NSURL URLWithString:self.personalInformation.userFace] placeholderImage:[UIImage imageNamed:@"holderface"] options:SDWebImageRefreshCached];
    
}
#pragma mark - 设置背景墙
- (void)setUpBackgroundWall{
    /** 创建背景墙 */
    self.backgroundWall = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 220)];
    self.backgroundWall.contentMode =UIViewContentModeScaleAspectFill;
    /** 把背景墙添加到tableView的头部*/
    self.tableView.tableHeaderView = self.backgroundWall;
    /** 给背景墙添加手势 更换图片 */
    //    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeImage:)];
    self.backgroundWall.userInteractionEnabled = YES;
    //    [self.backgroundWall addGestureRecognizer:tap];
    /** 头像 */
    self.userImage = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 60) / 2, (self.backgroundWall.frame.size.height - 60) / 2 - 30, 60, 60)];
    self.userImage.layer.cornerRadius = 30;
    self.userImage.userInteractionEnabled = YES;
    self.userImage.clipsToBounds = YES;
    /** 给头像添加手势 更换头像图片 */
    UITapGestureRecognizer *userImageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeImage:)];
    [self.userImage addGestureRecognizer:userImageTap];
    [self.backgroundWall addSubview:self.userImage];
    /** 用户名 */
    self.userNameLabel = [[DALabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 200) / 2, self.userImage.frame.origin.y + self.userImage.frame.size.height + 10, 200, 20)];
    if (![self.personalInformation.userName isKindOfClass:[NSNull class]]) {
        [self.userNameLabel setText:self.personalInformation.userName fitToContent:YES];
        self.userNameLabel.textColor = [UIColor whiteColor];
        self.userNameLabel.textAlignment = NSTextAlignmentCenter;
        self.userNameLabel.font = [UIFont boldSystemFontOfSize:17];
    }
    [self.backgroundWall addSubview:self.userNameLabel];
    /** 签名 */
    self.personalSignatureLabel = [[DALabel alloc]initWithFrame:CGRectMake(self.userNameLabel.frame.origin.x, self.userNameLabel.frame.origin.y + self.userNameLabel.frame.size.height + 5, self.userNameLabel.frame.size.width, self.userNameLabel.frame.size.height)];
    
    if (![self.personalInformation.userSign isKindOfClass:[NSNull class]] ) {
        [self.personalSignatureLabel setText:self.personalInformation.userSign fitToContent:YES];
        self.personalSignatureLabel.textAlignment = NSTextAlignmentCenter;
        self.personalSignatureLabel.font = [UIFont systemFontOfSize:12];
        self.personalSignatureLabel.textColor = [UIColor whiteColor];
    }
    [self.backgroundWall addSubview:self.personalSignatureLabel];
    
    bookSegment = [[UISegmentedControl alloc]initWithFrame:CGRectMake(-5, 180, SCREENWIDTH +10, 40)];
    [bookSegment insertSegmentWithTitle:@"\t\t\t\tTimeline" atIndex:0 animated:NO];
    NSString *bookManager = NSLocalizedString(@"bookManagement", nil);
    [bookSegment insertSegmentWithTitle:bookManager atIndex:1 animated:NO];
    NSString *fileManager = NSLocalizedString(@"My file", nil);
    [bookSegment insertSegmentWithTitle:fileManager atIndex:2 animated:NO];
    
    bookSegment.backgroundColor = [UIColor whiteColor];
    bookSegment.tintColor = [UIColor supportGreenColor];
    bookSegment.layer.borderColor = [UIColor whiteColor].CGColor;
    bookSegment.layer.borderWidth = 1;
    bookSegment.selectedSegmentIndex = 0;
    //    bookSegment.alpha = 0.9;
    [self.backgroundWall addSubview:bookSegment];
    //  ICON
    self.timelineIcon = [[UIImageView alloc]initWithFrame:CGRectMake(10, 192, 15, 15)];
    self.timelineIcon.image = [UIImage imageNamed:@"timeline2"];
    [self.backgroundWall addSubview:self.timelineIcon];
    self.bookManagmentIcon = [[UIImageView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/3+ 10, 193, 18, 13)];
    self.bookManagmentIcon.image = [UIImage imageNamed:@"book@3x2"];
    [self.backgroundWall addSubview:self.bookManagmentIcon];
    self.fileManagmentIcon = [[UIImageView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width*2/3+10, 193, 13, 15)];
    self.fileManagmentIcon.image = [UIImage imageNamed:@"file_icon2"];
    [self.backgroundWall addSubview:self.fileManagmentIcon];
    
    
    [bookSegment addTarget:self action:@selector(bookSegmentValueChanged) forControlEvents:UIControlEventValueChanged];
    
    UIButton *settingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [settingButton setImage:[UIImage imageNamed:@"system"] forState:UIControlStateNormal];
    settingButton.frame = CGRectMake(SCREENWIDTH - 40, 20, 40,40);
    [settingButton setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [self.backgroundWall addSubview:settingButton];
    [settingButton addTarget:self action:@selector(systemSetting) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *collectionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [collectionButton setImage:[UIImage imageNamed:@"discollect"] forState:UIControlStateNormal];
    collectionButton.frame = CGRectMake(SCREENWIDTH-40, 130, 40, 40);
    [collectionButton setImageEdgeInsets:UIEdgeInsetsMake(7, 7, 7, 7)];
    [self.backgroundWall addSubview:collectionButton];
    [collectionButton addTarget:self action:@selector(myCollection) forControlEvents:UIControlEventTouchUpInside];
    
}
#pragma mark - 个人时间轴 和图书管理 切换
- (void)bookSegmentValueChanged{
    if(bookSegment.selectedSegmentIndex == 0){
        self.timelineIcon.image = [UIImage imageNamed:@"timeline2"];
        self.bookManagmentIcon.image = [UIImage imageNamed:@"book@3x2"];
        self.fileManagmentIcon.image = [UIImage imageNamed:@"file_icon2"];
        self.changeStatus = 0;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        label.hidden = YES;
        // self.tableView.mj_footer.hidden = YES;
        self.tableView.editing = NO;
        [self.tableView reloadData];
    }else if(bookSegment.selectedSegmentIndex == 1){
        self.timelineIcon.image = [UIImage imageNamed:@"timeline"];
        self.bookManagmentIcon.image = [UIImage imageNamed:@"book@3x"];
        self.fileManagmentIcon.image = [UIImage imageNamed:@"file_icon2"];
        self.changeStatus = 1;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        label.hidden = YES;
        if (self.threeBookMnanageArray.count == 0) {
            [self.tableView.mj_header beginRefreshing];
        }
        self.tableView.mj_footer.hidden = YES;
        self.tableView.editing = NO;
        [self.tableView reloadData];
    }else{
        self.timelineIcon.image = [UIImage imageNamed:@"timeline"];
        self.bookManagmentIcon.image = [UIImage imageNamed:@"book@3x2"];
        self.fileManagmentIcon.image = [UIImage imageNamed:@"file_icon"];
        self.changeStatus = 2;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        if (self.fileManagmentArray.count == 0) {
            [self.tableView.mj_header beginRefreshing];
        }
        self.tableView.mj_footer.hidden = YES;
        label.hidden = YES;
        [self.tableView reloadData];
    }
}
#pragma mark - 系统设置触发方法
- (void)systemSetting{
    [self performSegueWithIdentifier:@"PERSON2SETTING" sender:nil];
}
- (void)myCollection{
    DACollectedFilesViewController *collectFile = [self.storyboard instantiateViewControllerWithIdentifier:@"ColectedFilesController"];
    collectFile.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:collectFile animated:YES];
}

#pragma mark - 搜索按钮触发的方法
- (void)searchClick:(UITapGestureRecognizer *)tap{
    NSLog(@"点击了搜索按钮");
}
#pragma mark - ShowAlert
- (void)showAlertWithContent:(NSString *)content{
    NSString *alerStr = NSLocalizedString(@"alert", nil);
    NSString *takePhoto = NSLocalizedString(@"takePhoto", nil);
    NSString *photoAlbum = NSLocalizedString(@"photoAlbum", nil);
    NSString *cancel = NSLocalizedString(@"cancel", nil);
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:alerStr message:content preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *TopAction = [UIAlertAction actionWithTitle:takePhoto style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        /** 调用拍照上传*/
        [self chooseTakePhoto];
    }];
    UIAlertAction *midAction = [UIAlertAction actionWithTitle:photoAlbum style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        /** 调用相册*/
        [self choosePhotoLibrary];
    }];
    UIAlertAction *bottom = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:TopAction];
    [alert addAction:midAction];
    [alert addAction:bottom];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 更换图片
- (void)changeImage:(UITapGestureRecognizer *)tap{
    if (tap.view == self.backgroundWall) {
        NSLog(@"更换背景图片");
        self.isSelectedBackgroundWall = YES;
        self.isSelectedUserImage = NO;
        [self showAlertWithContent:@"更换背景图片"];
    }else if (tap.view == self.userImage){
        NSLog(@"更换头像");
        self.isSelectedBackgroundWall = NO;
        self.isSelectedUserImage = YES;
        NSString *changeUserImage = NSLocalizedString(@"changeHeaderImage", nil);
        [self showAlertWithContent:changeUserImage];
    }
}
#pragma mark - 选择相册上传
- (void)choosePhotoLibrary{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    picker.delegate = self;
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:^{
        NSLog(@"445555iiio");}];
}
#pragma mark - 选择拍照上传
- (void)chooseTakePhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    picker.delegate = self;
    picker.allowsEditing = YES;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    [self presentViewController:picker animated:YES completion:^{}];
}
#pragma mark - 相册的协议方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    /** 判断数据源是否是相机*/
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        if (image != nil ) {
            if (self.isSelectedBackgroundWall) {
                self.backgroundWall.image = image;
            }else if (self.isSelectedUserImage){
                self.userImage.image = image;
            }
            self.selectImage = image;
            // 将拍照后的图片 写入相册
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }
    }
    /** 判断数据源是否是相册*/
    else if(picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){
        UIImage *temp = [info objectForKey:UIImagePickerControllerEditedImage];
        if (temp != nil) {
            // 判断是不是选择了背景墙
            if (self.isSelectedBackgroundWall) {
                self.backgroundWall.image = temp;
            }else if (self.isSelectedUserImage){
                self.userImage.image = temp;
            }
            self.selectImage = temp;
        }
    }
    // 压缩图片
    // CGSize imageSize = self.selectImage.size;
    CGFloat targetWidth = 200;
    CGFloat targetHeight = 200;
    
    CGSize newSize = CGSizeMake(targetWidth, targetHeight);
    UIGraphicsBeginImageContext(newSize);
    [self.selectImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSData *data;
    if (UIImagePNGRepresentation(newImage)) {
        data = UIImagePNGRepresentation(newImage);
    }else{
        data = UIImageJPEGRepresentation(newImage, 1.0);
    }
    self.backgroundWall.clipsToBounds = YES;
    self.userImage.clipsToBounds = YES;
    if (self.isSelectedBackgroundWall) {
        [[NSFileManager defaultManager] createFileAtPath:self.backgroundImagePath contents:data attributes:nil];
    }else if (self.isSelectedUserImage){
        [[NSFileManager defaultManager] createFileAtPath:self.userImagePath contents:data attributes:nil];
    }
    [self dismissViewControllerAnimated:YES completion:^{
        [self updateImageToServer:data];
    }];
}
- (void)updateImageToServer:(NSData *)data{
    NSString *str = NSLocalizedString(@"userPhotoIsUploading", nil);
    [SVProgressHUD showWithStatus:str];
    NSString *url = DAChangeImageURL;
    NSString *type;
    if (self.isSelectedBackgroundWall) {
        type = @"1";
    } else if (self.isSelectedUserImage){
        type = @"2";
    }
    NSString *base64String = [data base64EncodedStringWithOptions:0];
    NSDictionary *dic = @{@"image":base64String,
                          @"userID":self.userID,
                          @"type":type};
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        
        if([result isKindOfClass:[NSDictionary class]]){
            NSString *key = result[@"result"];
            if (key) {
                NSLog(@"图片成功上传");
                [[SDImageCache sharedImageCache]storeImageDataToDisk:data forKey:key];
                NSString *str = NSLocalizedString(@"isUploadingSuccess", nil);
                [SVProgressHUD showSuccessWithStatus:str];
            } else {
                NSLog(@"图片上传失败");
                NSString *str = NSLocalizedString(@"isUploadingFailed", nil);
                [SVProgressHUD showErrorWithStatus:str];
            }
            NSLog(@"key:%@", key);
        }else{
            NSString *str = NSLocalizedString(@"isUploadingFailed", nil);
            [SVProgressHUD showErrorWithStatus:str];
        }
    }];
}
#pragma mark - 把头像和背景图片也存到本地
- (void)archiveUserImageAndBackgroundWall{
    
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSLog(@"已保存");
}
#pragma mark - 创建图片路径
- (void)creatImagePath{
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *imagePath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    [[NSFileManager defaultManager] createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
    self.backgroundImagePath = [imagePath stringByAppendingPathComponent:@"BackgroundImage.png"];
    self.userImagePath = [imagePath stringByAppendingPathComponent:@"UserImage.png"];
}
#pragma mark - 修改状态栏的颜色
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
#pragma mark - 个人借阅历史的图书的点击协议方法
- (void)clickBookImage:(NSString *)bookId{
    [self showGrayView];
    [self creatBookDetailView];
    self.detailView.bookID = bookId;
    self.detailView.isSelectHomePageTimeLine = NO;
    self.detailView.isSelectPersonalPage = YES;
    self.detailView.isSelectOtherPersonalPage = NO;
    [self.detailView prepareData];
    [self.detailView.scrollView setContentOffset:CGPointMake(0, 0)];
}
#pragma mark - 归还的cell 点击图书image的协议方法
- (void)personalBackBookClickBookImage:(NSString *)bookID{
    [self showGrayView];
    [self creatBookDetailView];
    self.detailView.bookID = bookID;
    self.detailView.isSelectHomePageTimeLine = NO;
    self.detailView.isSelectPersonalPage = YES;
    self.detailView.isSelectOtherPersonalPage = NO;
    [self.detailView prepareData];
    [self.detailView.scrollView setContentOffset:CGPointMake(0, 0)];
}
#pragma mark - 弹出灰色蒙版
- (void)showGrayView{
    /** 灰色蒙版*/
    self.grayView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.grayView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:self.grayView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickClose:)];
    [self.grayView addGestureRecognizer:tap];
}
#pragma mark - 弹出的图书详情页面
- (void)buildBookDetailView{
    self.detailView = [self.storyboard instantiateViewControllerWithIdentifier:@"BOOKDETAIL"];
    self.detailView.view.frame = CGRectMake(20, 80, self.view.frame.size.width - 40, 400 * HEIGHTTOFIT5s);
    [[UIApplication sharedApplication].keyWindow addSubview:self.detailView.view];
    self.detailView.view.hidden = YES;
}
- (void)creatBookDetailView{
    self.detailView.view.hidden = NO;
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self.detailView.view];
    /** 添加动画*/
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.detailView.view cache:YES];
    [UIView commitAnimations];
    /** 消失手势*/
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickClose:)];
    [self.detailView.closeImage addGestureRecognizer:tap];
    /** bookImage手势*/
    UITapGestureRecognizer *bookImageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickBookImageShow:)];
    self.detailView.bookImage.userInteractionEnabled = YES;
    [self.detailView.bookImage addGestureRecognizer:bookImageTap];
}
#pragma mark - 点击closeImage触发的方法
- (void)clickClose:(UITapGestureRecognizer *)tap{
    NSLog(@"关闭");
    self.detailView.view.hidden = YES;
    [self.grayView removeFromSuperview];
    [self.InputBookLostReasonView removeFromSuperview];
    [self.rateMessageView removeFromSuperview];
}
#pragma mark - 点击bookImage触发的方法
- (void)clickBookImageShow:(UITapGestureRecognizer *)tap{
    /** 跳转到图书详情页面*/
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    DASearchBookDetailViewController *detailVC = [story instantiateViewControllerWithIdentifier:@"SEARCHBOOKDETAIL"];
    detailVC.bookID = self.detailView.bookID;
    [self clickClose:nil];
    detailVC.hidesBottomBarWhenPushed = YES;
    /** 转场动画
     *CTransition *transition = [CATransition animation];
     *transition.duration = 1.0f;
     *transition.type = @"rippleEffect";
     *transition.subtype = kCATransitionFromTop;
     *[self.navigationController.view.layer addAnimation:transition forKey:nil];
     */
    /** push之前先关掉隐藏导航栏*/
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController pushViewController:detailVC animated:YES];
}
#pragma mark - segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"PERSON2SETTING"]){
        DAPersonalSettingViewController *settingVC = [segue destinationViewController];
        settingVC.navigationController.navigationBarHidden = NO;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"hideTabBar" object:nil];
    }
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    // self.view = nil;
    [self.view removeFromSuperview];
    //    self.detailView = nil;
    //    [self.detailView.view removeFromSuperview];
    //    [self.statusView removeFromSuperview];
}
#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    topView.alpha = (scrollView.contentOffset.y - 150)/100;
}
#pragma mark - 个人时间轴 数据
- (void)preparePersonalTimelineData{
    NSString *url = DAPersonalTimeLineURL;
    NSString *pageNumber = [NSString stringWithFormat:@"%ld", (long)self.personalTimelinePageNumber];
    NSDictionary *dic = @{@"page": pageNumber,
                          @"userID": self.userID};
    NSLog(@"个人页面的时间轴的 pageNumer %ld,", (long)self.personalTimelinePageNumber);
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        // 数据异常判断
        if (result && [result[@"result"] isKindOfClass:[NSArray class]]) {
            DAHomePageTimeLineModel *timeModel = [[DAHomePageTimeLineModel alloc]init];
            NSArray *array  = [timeModel returnModelInArrayWithDic:result[@"result"]];
            if (array.count < 20) {
                // self.footer.stateLabel.hidden = YES;
                //self.footer.refreshingTitleHidden = YES;
                weakSelf.tableView.mj_footer.hidden = YES;
            }else{
                // self.footer.stateLabel.hidden = NO;
                //self.footer.refreshingTitleHidden = NO;
                weakSelf.tableView.mj_footer.hidden = NO;
            }
            if (weakSelf.isPersonalTimeLineRefresh) {
                weakSelf.personalDataArray = [NSMutableArray array];
                [weakSelf.personalDataArray addObjectsFromArray:array];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                //weakSelf.personalTimelinePageNumber++;
                weakSelf.personalInformation.userBackground = result[@"userBackground"];
                weakSelf.personalInformation.userFace = result[@"userFace"];
                weakSelf.personalInformation.userName = result[@"userName"];
                weakSelf.personalInformation.userSign = result[@"userSign"];
                // 更新个人信息
                [weakSelf setupBackWall];
                [weakSelf updateUserInfo];
                [weakSelf archiveToLocal];
            }else{
                if (array.count > 0) {
                    [weakSelf.personalDataArray addObjectsFromArray:array];
                    [weakSelf.tableView reloadData];
                    //weakSelf.personalTimelinePageNumber++;
                }
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            // [self finishLoadDataMBProgress];
        }else{
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
            }
            else{
                [SVProgressHUD showErrorWithStatus:self.requestFailed];
            }
            //[self finishLoadDataMBProgress];
            NSLog(@"DAPersonalTimeLineURL：没有数据");
        }
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - 用户收藏的文件
- (void)prepareCollectFiles{
    NSString *url = DAUserCollectFiles;
    NSDictionary *dic = @{@"collectUserID":self.userID};
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSArray class]] && [result[@"result"] count]>0 ) {
            DAUserFileModel *model = [[DAUserFileModel alloc]init];
            self.collectFiles = [model returnModelInArrayWithDic:result[@"result"]];
        }else{
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
                // [self.tableView.mj_header endRefreshing];
            }
            else if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
                // [self.tableView.mj_header endRefreshing];
            }
            else if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
                // [self.tableView.mj_header endRefreshing];
            }
            else{
                [SVProgressHUD showErrorWithStatus:self.requestFailed];
                // [self.tableView.mj_header endRefreshing];
            }
        }
        
    }];
}


#pragma mark - 把取出来的数据在存到本地
- (void)archiveToLocal{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"DALogin"];
    [NSKeyedArchiver archiveRootObject:self.personalInformation toFile:filePath];
    //  NSLog(@"~~~~~~~~%@", self.personalInformation.userFace);
}
#pragma mark - 个人上传的文件
- (void)prepareFileData{
    NSString *url = DAUserFileURL;
    NSDictionary *dic = @{@"userID":self.userID};
    NSLog(@"User ID %@ ",self.userID);
    [self dataHandelWithUrl:url parame:dic];
}

- (void)dataHandelWithUrl:(NSString *)url parame:(NSDictionary *)dic{
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSArray class]] && [result[@"result"] count] > 0){
            [weakSelf dataTransFormModel:result[@"result"]];
        }else{
            label.hidden = YES;
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
            }
            else{
                if(self.fileManagmentArray.count == 0){
                    label.hidden = NO;
                    //[SVProgressHUD dismiss];
                    [self.tableView.mj_header endRefreshing];
                }else{
                    [SVProgressHUD showErrorWithStatus:self.requestFailed];
                    [self.tableView.mj_header endRefreshing];
                }
            }
        }
    }];
}
- (void)dataTransFormModel:(NSArray *)resultArray{
    DAUserFileModel *userFileModel = [[DAUserFileModel alloc]init];
    NSArray *array = [userFileModel returnModelInArrayWithDic:resultArray];
    
    self.fileManagmentArray = [NSMutableArray array];
    [self.fileManagmentArray addObjectsFromArray:array];
    [self arraySort];
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
    
}
#pragma mark - 获取文件名首字母
- (void)arraySort{
    self.keys = [NSMutableArray array];
    self.indexArray = [NSMutableArray array];
    self.userDic = [NSMutableDictionary dictionary];
    self.charactorArray = [NSMutableArray array];
    for (char a = '0'; a <= '9'; a++) {
        [self.charactorArray addObject:[NSString stringWithFormat:@"%c",a]];
    }
    for (char a = 'A'; a <= 'Z'; a++) {
        [self.charactorArray addObject:[NSString stringWithFormat:@"%c",a]];
    }
    for (DAPersonalFileListModel *userFileModel in self.fileManagmentArray) {
        NSString *key = [self firstCharactor:userFileModel.fileName];
        [self.keys addObject:key];
    }
    for (NSString *key in self.keys) {
        NSMutableArray *arr = [NSMutableArray array];
        [self.userDic setObject:arr forKey:key];
    }
    for (DAPersonalFileListModel *userFileModel in self.fileManagmentArray) {
        NSString *key = [self firstCharactor:userFileModel.fileName];
        //NSLog(@"file名 %@",userFileModel.fileName);
        [self.userDic[key] addObject:userFileModel];
    }
    self.indexArray = [[self.userDic.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]mutableCopy];
    if ([self.indexArray containsObject:@"#"]) {
        [self.indexArray removeObject:@"#"];
        [self.indexArray addObject:@"#"];
    }
}
#pragma mark - 获取首字母方法
- (NSString *)firstCharactor:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, YES);
    NSString *largeStr = [str capitalizedString];
    NSString *firstStr;
    if (string.length != 0) {
        firstStr = [largeStr substringToIndex:1];
    }
    BOOL isContain = [self.charactorArray containsObject:firstStr];
    if (isContain == NO || [firstStr isEqualToString:@""]) {
        firstStr = @"#";
    }
    return firstStr;
}


#pragma mark - 个人借的书的数据
- (void)getPersonalBorrowBook{
    NSString *url = DAPersonalBorrowBookURL;
    NSString *pageNumber = [NSString stringWithFormat:@"%ld", (long)self.personalBookManagementPageNumber];
    NSDictionary *dic = @{@"userID": self.userID,
                          @"page": pageNumber};
    NSLog(@"个人借的书的pageNumber %ld", (long)self.personalBookManagementPageNumber);
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        //数据异常判断
        if ( result && [result[@"result"] isKindOfClass:[NSArray class]]) {
            DAPersonalBookManageModel *bookManageModel = [[DAPersonalBookManageModel alloc]init];
            NSMutableArray *array = [bookManageModel returnModelInArrayWithArray:result[@"result"]];
            NSArray *dataArray = [self arrWithModel:array];
            if (array.count < 21) {
                // self.footer.stateLabel.hidden = YES;
                weakSelf.tableView.mj_footer.hidden = YES;
            }else{
                //  self.footer.stateLabel.hidden = NO;
                weakSelf.tableView.mj_footer.hidden = NO;
            }
            if (weakSelf.isPersonalBookManagementRefresh) {
                weakSelf.threeBookMnanageArray = [NSMutableArray array];
                [weakSelf.threeBookMnanageArray addObjectsFromArray:dataArray];
                [weakSelf.tableView reloadData];
                //weakSelf.personalBookManagementPageNumber++;
                [weakSelf.tableView.mj_header endRefreshing];
            }else{
                if (array.count > 0) {
                    [weakSelf.threeBookMnanageArray addObjectsFromArray:dataArray];
                    [weakSelf.tableView reloadData];
                    //weakSelf.personalBookManagementPageNumber++;
                    // NSLog(@"____%@", dataArray);
                }
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }else {
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
            }
            
            else{
                [SVProgressHUD showErrorWithStatus:self.requestFailed];
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            
        }
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        // NSLog(@"%@", result);
    }];
}
#pragma mark - 数据处理
- (NSMutableArray *)arrWithModel:(NSMutableArray *)arr{
    NSMutableArray *newArr = [NSMutableArray array];
    NSMutableArray *lastArr = [NSMutableArray array];
    NSUInteger index = 0;
    for (NSUInteger i = 0; i < arr.count; i++) {
        if (index != 3) {
            [newArr addObject:arr[i]];
        }else {
            [lastArr addObject:newArr];
            newArr = [NSMutableArray array];
            i--;
            index = -1;
        }
        index++;
    }
    if (arr.count % 3 != 0) {
        newArr = [NSMutableArray array];
        for (NSUInteger j = arr.count - (arr.count % 3); j < arr.count; j++) {
            [newArr addObject:arr[j]];
        }
    }
    [lastArr addObject:newArr];
    return lastArr;
}
#pragma mark - 还书的协议方法
- (void)backBookWithBorrowID:(NSString *)borrowID{
    //    [self alertSheetShow:@"提示" message:@"是否确认归还"];
    //    __weak typeof(self) weakSelf = self;
    //    self.backBookBlock = ^(){
    //      [weakSelf personalBackBook:borrowID];
    //    };
    //
    // [self rateMessageViewRiseUp];
    self.borrowID = borrowID;
    [self creatRateMessageView];
}
#pragma mark - 调用还书的接口
- (void)personalBackBook:(NSString *)borrowID rateNum:(NSString *)rateNum {
    //[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD show];
    NSString *url = DABorrow_BackURL;
    NSString *text = self.rateMessageView.textView.text;
    NSString *backBookisSuccess = NSLocalizedString(@"backBookIsSuccess", nil);
    NSString *backBookIsFailed = NSLocalizedString(@"backBookFailed", nil);
    
    NSMutableDictionary *dic = [@{@"borrowID": borrowID}mutableCopy];
    if (rateNum != nil) {
        [dic setObject:rateNum forKey:@"rateNum"];
    }
    if (self.rateMessageView.textView.text != nil) {
        [dic setObject:text forKey:@"rateMessage"];
    }
    NSLog(@"%@", dic);
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isEqualToString:@"true"]) {
            [weakSelf getPersonalBorrowBook];
            [weakSelf clickCancel];
            [SVProgressHUD showSuccessWithStatus:backBookisSuccess];
            [weakSelf.tableView reloadData];
            [weakSelf.tableView.mj_header beginRefreshing];
            
        }else{
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
            }
            else{
                
                [SVProgressHUD showErrorWithStatus:backBookIsFailed];
            }
            
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf finishLoadDataMBProgress];
        });
    }];
}
#pragma mark - 创建评价的view
- (void)creatRateMessageView{
    self.rateMessageView = [[DARateNumberAndRateMessage alloc]initWithFrame:CGRectMake(20, [UIScreen mainScreen].bounds.size.height - 260, [UIScreen mainScreen].bounds.size.width - 40, 260)];
    self.rateMessageView.tag = 1002;
    self.rateMessageView.hidden = NO;
    self.rateMessageView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:self.rateMessageView];
    [self rateMessageViewRiseUp];
}
#pragma mark - 监听评分的view弹起
- (void)rateMessageViewRiseUp{
    // 监听键盘弹起
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rateMessViewKeyboardRise:) name:UIKeyboardWillShowNotification object:nil];
    // 监听键盘收回
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rateMessViewKeyboardHidden:) name:UIKeyboardWillHideNotification object:nil];
    // self.rateMessageView.hidden = YES;
    [self.rateMessageView.textView becomeFirstResponder];
    self.statusView.hidden = YES;
}
- (void)rateMessViewKeyboardRise:(NSNotification *)notif{
    // self.rateMessageView.hidden = NO;
    CGRect frame = [[[notif userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:0.2 animations:^{
        self.rateMessageView.frame = CGRectMake(20, [UIScreen mainScreen].bounds.size.height - frame.size.height - 260, self.view.frame.size.width - 40, 260);
    }];
    NSLog(@"评分的view弹起");
}
- (void)rateMessViewKeyboardHidden:(NSNotification *)notif{
    [UIView animateWithDuration:0.2 animations:^{
        self.rateMessageView.frame = CGRectMake(20, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width - 40, 260);
    } completion:^(BOOL finished) {
        //self.statusView.hidden = NO;
        self.rateMessageView.hidden = YES;
    }];
    NSLog(@"评分的view 键盘收回");
}

#pragma mark - rateMessageViewDelegate
- (void)backBookWithRateNumber:(NSString *)rateNumber{
    // 调用还书接口
    [self personalBackBook:self.borrowID rateNum:rateNumber];
}
// 点击了rateMessageView的closeImage
- (void)clickRateMessageViewCloseView{
    
    [self.rateMessageView.textView resignFirstResponder];
    self.statusView.hidden = NO;
}

#pragma mark - 延期的协议方法
- (void)bookDelayWithBorrowID:(NSString *)borrowID{
    [self showDelayView];
    self.borrowExtendBookID = borrowID;
}
- (void)borrowExtend:(NSString *)time {
    NSLog(@"延期借阅");
    [self personalBorrowExtend:self.borrowExtendBookID time:time];
}
#pragma mark - 调用延期的协议方法
- (void)personalBorrowExtend:(NSString *)borrowID time:(NSString *)time{
    NSString *url = DABorrowBookExtendURL;
    NSDictionary *dic = @{@"userID": self.userID,
                          @"borrowID": borrowID,
                          @"borrowExtend": time};
    NSString *isDelayTimeSuccess = NSLocalizedString(@"delayTimeIsSuccess", nil);
    NSString *isDelayTimeFailed = NSLocalizedString(@"delayTimeIsFailed", nil);
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if (result && [result isKindOfClass:[NSDictionary class]]) {
            if ([result[@"result"] isEqualToString:@"true"]) {
                NSLog(@"延期成功");
                [SVProgressHUD showSuccessWithStatus:isDelayTimeSuccess];
                [weakSelf clickBookDelayCloseImage];
                [weakSelf clickCancel];
                [weakSelf.tableView.mj_header beginRefreshing];
            }else{
                
                if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                    [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
                }
                if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                    [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
                }
                if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                    [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
                }
                else{
                    NSLog(@"延期失败");
                    [SVProgressHUD showErrorWithStatus:isDelayTimeFailed];
                    [weakSelf clickBookDelayCloseImage];
                    [weakSelf clickCancel];
                }
            }
        }
        
    }];
}
#pragma mark - 延期选择的view
- (void)creatDelayView{
    self.bookDelayView = [[DABookDelayView alloc]initWithFrame:self.statusView.frame];
    self.bookDelayView.tag = 1001;
    self.bookDelayView.hidden = YES;
    self.bookDelayView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:self.bookDelayView];
}
- (void)showDelayView{
    self.bookDelayView.hidden = NO;
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self.bookDelayView];
    /** 添加动画*/
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.bookDelayView cache:YES];
    [UIView commitAnimations];
}
#pragma mark - 延期view 的协议方法
- (void)clickBookDelayCloseImage{
    /** 添加动画*/
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.bookDelayView cache:YES];
    [UIView commitAnimations];
    self.bookDelayView.hidden = YES;
}
#pragma  mark- 报失的协议方法
- (void)bookLost:(NSString *)borrowID{
    // 监听键盘弹起
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardRise:) name:UIKeyboardWillShowNotification object:nil];
    // 监听键盘收回
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardWillHideNotification object:nil];
    self.InputBookLostReasonView.hidden = NO;
    [self.InputBookLostReasonView.textField becomeFirstResponder];
    self.InputBookLostReasonView.bookID = borrowID;
}

#pragma mark - 调用报失的接口
- (void)prepareBookLost:(NSString *)borrowID lostReason:(NSString *)reason{
    // [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSString *url = DABorrow_LoseURL;
    NSDictionary *dic = @{@"borrowID": borrowID,
                          @"borrowReason": reason};
    NSString *isLostSuccess = NSLocalizedString(@"lostIsSuccess", nil);
    NSString *isLostFailed = NSLocalizedString(@"lostIsFailed", nil);
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isEqualToString:@"true"]) {
            [SVProgressHUD showSuccessWithStatus:isLostSuccess];
            [weakSelf getPersonalBorrowBook];
            // [self.tableView reloadData];
            [weakSelf clickCancel];
            [weakSelf.tableView.mj_header beginRefreshing];
        }else{
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
            }
            else{
                [SVProgressHUD showErrorWithStatus:isLostFailed];
                [weakSelf.InputBookLostReasonView.textField resignFirstResponder];
                [weakSelf.InputBookLostReasonView removeFromSuperview];
            }
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf finishLoadDataMBProgress];
        });
        
    }];
}
#pragma mark - 输入后点击发送 的协议方法
- (void)postBookLostMessage{
    [self prepareBookLost:self.InputBookLostReasonView.bookID lostReason:self.InputBookLostReasonView.textField.text];
}
#pragma mark - 创建报失的输入的view
- (void)creatBookLostInputReasonView{
    self.InputBookLostReasonView = [[DAInputBookLostReasonView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 40 , [UIScreen mainScreen].bounds.size.width, 40)];
    self.InputBookLostReasonView.backgroundColor = [UIColor whiteColor];
    self.InputBookLostReasonView.hidden = YES;
    self.InputBookLostReasonView.delegate = self;
    // [self.InputBookLostReasonView.userImageView sd_setImageWithURL:[NSURL URLWithString:self.personalInformation.userFace] placeholderImage:nil];
    [self.InputBookLostReasonView.userImageView sd_setImageWithURL:[NSURL URLWithString:self.personalInformation.userFace] placeholderImage:[UIImage imageNamed:@"holderface"] options:SDWebImageRefreshCached];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.InputBookLostReasonView];
}
#pragma mark - 把输入框弹起
- (void)keyboardRise:(NSNotification *)notif{
    CGRect frame =  [[[notif userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:0.2 animations:^{
        self.InputBookLostReasonView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height -frame.size.height - 40, self.view.frame.size.width, 40);
    }];
    NSLog(@"键盘弹起");
    //    CGFloat height;
    //    if (self.view.bounds.size.width < 375) {
    //         height = 290;
    //    }else{
    //        height = 320;
    //    }
    //    [UIView animateWithDuration:0.2 animations:^{
    //        self.statusView.frame = CGRectMake(20, self.view.bounds.size.height - 290 - frame.size.height - 40, self.view.frame.size.width - 40, height);
    //    } completion:^(BOOL finished) {
    //
    //    }];
    // 键盘升起的时候 让 归还 延期 报失的按钮不可点击
    self.statusView.backButton.userInteractionEnabled = NO;
    self.statusView.delayButton.userInteractionEnabled = NO;
    self.statusView.lostButton.userInteractionEnabled = NO;
    
}
#pragma mark - 键盘收回
- (void)keyboardHidden:(NSNotification *)notif{
    //    CGFloat height;
    //    if (self.view.bounds.size.width < 375) {
    //        height = 290;
    //    }else{
    //        height = 320;
    //    }
    [UIView animateWithDuration:0.2 animations:^{
        self.InputBookLostReasonView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height + 40, [UIScreen mainScreen].bounds.size.width, 40);
    } completion:^(BOOL finished) {
        // 键盘落下之后 让 归还 延期 报失可以点击
        self.statusView.backButton.userInteractionEnabled = YES;
        self.statusView.delayButton.userInteractionEnabled = YES;
        self.statusView.lostButton.userInteractionEnabled = YES;
        self.InputBookLostReasonView.hidden = YES;
    }];
    
    //    [UIView animateWithDuration:0.2 animations:^{
    //        self.statusView.frame = CGRectMake(20, self.view.center.y - 160 *(self.view.bounds.size.width / 375), self.view.frame.size.width - 40, height);
    //    } completion:^(BOOL finished) {
    //
    //    }];
    
    NSLog(@"键盘收回");
}


#pragma mark - mark - alertSheet
- (void)alertSheetShow:(NSString *)title message:(NSString *)message{
    NSString *sure = NSLocalizedString(@"Sure", nil);
    NSString *cancel = NSLocalizedString(@"cancel", nil);
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message: message preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *topAction = [UIAlertAction actionWithTitle:sure style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.backBookBlock();
        
    }];
    UIAlertAction *bottomAction = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        self.statusView.hidden = NO;
        [self showBackView];
        [self showDetailView];
        [self creatBookLostInputReasonView];
    }];
    [alert addAction:topAction];
    [alert addAction:bottomAction];
    
    self.statusView.hidden = YES;
    [self.backView removeFromSuperview];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GRAYVIEWREMOVE" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"TurnPersonalPage" object:nil];
}
#pragma mark - 跳转到其他个人页面
- (void)turnPersonal:(NSString *)userID{
    DAOtherPersonalViewController *otherPersonal = [self.storyboard instantiateViewControllerWithIdentifier:@"OTHERPERSONAL"];
    otherPersonal.hidesBottomBarWhenPushed = YES;
    otherPersonal.otherUserID = userID;
    [self.navigationController pushViewController:otherPersonal animated:YES];
}


#pragma mark - PersonalFileUploadDelagate 点击上传的文件的图片
- (void)personalOpenFieldWithModel:(DAHomePageTimeLineModel *)model{
    // TODO
    //文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.timelinefolderName,model.timelinefileExtend];
    NSLog(@"文件保存路径 %@",documentsDirectory);
    
    //文件下载路径
    NSString *str = model.timelinefileurl;
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
    NSURL *url = [NSURL URLWithString:encodedString];
    
    //判断文件在本地是否存在
    BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.timelinefolderName,model.timelinefileExtend] inPath:documentsDirectory];
    if(isExist){
        NSLog(@"Timeline文件可以直接打开");
        DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
        webFile.fileUrl = filePath;
        webFile.fileID = model.fileID;
        webFile.filefolderName = model.timelinefolderName;
        webFile.hidesBottomBarWhenPushed = YES;
        self.navigationController.navigationBarHidden = NO;
        [self.navigationController pushViewController:webFile animated:YES];
    }else{
        //下载文件
        NSLog(@"TimeLine下载文件");
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
            [self downLoadFile:[NSString stringWithFormat:@"%@.%@",model.timelinefolderName,model.timelinefileExtend] saveInPath:documentsDirectory fromURL:url];
        });
    }
    
    //    DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
    //    webFile.fileUrl = model.timelinefileurl;
    //    webFile.fileName = model.timelineMessage;
    //    webFile.fileExtend = model.timelinefileExtend;
    //    webFile.fileSaveName = model.timelinefolderName;
    //    webFile.hidesBottomBarWhenPushed = YES;
    //    self.navigationController.navigationBarHidden = NO;
    //    [self.navigationController pushViewController:webFile animated:YES];
    
}

#pragma mark - 判断沙盒里是否有这个文件
-(BOOL)isFileExist:(NSString *)fileName inPath:(NSString *)path{
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    //  NSLog(@"该文件：%@",result?@"有！！":@"不存在");
    return result;
}

#pragma mark - 下载文件
- (void)downLoadFile:(NSString *)fileName saveInPath:(NSString *)path fromURL:(NSURL *)url{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@", path, fileName];
    // NSURL *url = [NSURL URLWithString:@"http://www.abc.com/test.mp4"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task =
    //    [manager downloadTaskWithRequest:request
    //                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    //                                return [NSURL fileURLWithPath:fullPath];
    //                            }
    //                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    //
    //                   }];
    
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        CGFloat count = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        //        if (self.isFinish == NO) {
        //            [SVProgressHUD  showProgress:count];
        //        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        // [self creatPreview];
    }];
    [task resume];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
